<template>
    <div>
        <!------用户管理查询按钮------>
        <div class="search">
            <el-input v-model="name" placeholder="请输入名字" suffix-icon="el-icon-search" style="width: 200px;"
                      @keyup.enter.native="loadPost">
            </el-input>

            <el-select v-model="userIdentity" filterable placeholder="请选择身份" style="margin-left: 5px;">
                <el-option
                        v-for="item in userIdentitys"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>

            <el-button type="primary" style="margin-left: 10px;" @click="loadPost">查询</el-button>
            <el-button type="success" @click="resetParam">重置</el-button>
            <el-button type="warning" style="margin-left: 10px;" @click="add">新增</el-button>
        </div>

        <!------信息展示列表------>
        <el-table :data="tableData"
                  :header-cell-style="{color:'#c71111'}">
            <el-table-column prop="id" label="ID" width="50">
            </el-table-column>

            <el-table-column prop="studentId" label="学号" width="140">
            </el-table-column>

            <el-table-column prop="name" label="姓名" width="120">
            </el-table-column>

            <el-table-column prop="sex" label="性别" width="90">
                <template slot-scope="scope">
                    <el-tag
                            :type="scope.row.sex === 1 ? 'primary' : 'success'"
                            disable-transitions>{{scope.row.sex === 1 ? '男' : '女'}}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="age" label="年龄" width="80">
            </el-table-column>

            <el-table-column prop="userIdentity" label="身份" width="160">
            </el-table-column>

            <el-table-column prop="organization" label="组织" width="200">
            </el-table-column>

            <el-table-column prop="operate" label="操作">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                    <el-popconfirm
                            title="确定删除吗？"
                            @confirm="del(scope.row.id)"
                            style="margin-left: 10px;">
                        <el-button slot="reference" size="small" type="danger">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>


        <!------分页查询------>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[2, 5, 10, 20,30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>


        <!------新增列表------>
        <el-dialog
                title="提示"
                :visible.sync="centerDialogVisible"
                width="30%"
                center>

            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="学号" prop="studentId">
                    <el-col :span="20">
                        <el-input v-model="form.studentId" :disabled="form.studentIdDisabled"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-col :span="20">
                        <el-input v-model="form.password"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item label="姓名" prop="name">
                    <el-col :span="20">
                        <el-input v-model="form.name"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item label="性别">
                    <el-radio-group v-model="form.sex">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="年龄" prop="age">
                    <el-col :span="20">
                        <el-input v-model="form.age"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item label="电话" prop="phoneNumber">
                    <el-col :span="20">
                        <el-input v-model="form.phoneNumber"></el-input>
                    </el-col>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {serverIp} from "../../public/config";

    export default {
        name: "Main",
        data() {
            let checkAge = (rule, value, callback) => {
                if (value > 150) {
                    callback(new Error('年龄输入过大'));
                } else {
                    callback();
                }
            };
            let checkDuplicate = (rule, value, callback) => {
                if (this.form.id) {
                    console.log('outoutoutout')
                    return callback();
                }
                this.$axios.get('http://'+ serverIp +':8090/users/findByStudentId?studentId=' + this.form.studentId)
                    .then(res => res.data)
                    .then(res => {
                        if (res.code != 200) {
                            callback()
                        } else {
                            callback(new Error('学号已经存在'));
                        }
                    })
            };
            return {
                serverIp:serverIp,
                users: JSON.parse(sessionStorage.getItem('CurUser')),
                tableData: [],
                pageSize: 5,
                pageNum: 1,
                total: 0,
                name: '',
                userIdentity: '',
                userIdentitys: [
                    {
                        value: '1',
                        label: '管理员'
                    }, {
                        value: '2',
                        label: '中共党员'
                    }, {
                        value: '3',
                        label: '中共预备党员'
                    }, {
                        value: '4',
                        label: '发展对象'
                    }, {
                        value: '5',
                        label: '积极分子'
                    }, {
                        value: '6',
                        label: '群众'
                    }
                ],
                centerDialogVisible: false,
                form: {
                    id: '',
                    studentId: '',
                    name: '',
                    sex: '',
                    age: '',
                    phoneNumber: '',
                    organization: '',
                    userIdentity: '6',
                    password: 'password',
                    studentIdDisabled: 'false',
                },
                rules: {
                    studentId: [
                        {required: true, message: '请输入学号', trigger: 'blur'},
                        {min: 12, max: 12, message: '长度为12个字符', trigger: 'blur'},
                        {validator: checkDuplicate, trigger: 'blur'}
                    ],
                    name: [
                        {required: true, message: '请输入名字', trigger: 'blur'}
                    ],
                    age: [
                        {required: true, message: '请输入年龄', trigger: 'blur'},
                        {min: 1, max: 3, message: '长度在 1 到 3 个位', trigger: 'blur'},
                        {pattern: /^([1-9][0-9]*){1,3}$/, message: '年龄必须为正整数字', trigger: "blur"},
                        {validator: checkAge, trigger: 'blur'}
                    ],
                    phoneNumber: [
                        {required: true, message: "手机号不能为空", trigger: "blur"},
                        {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
                    ]
                }

            };
        },
        methods: {
            mounted() {
                // 获取当前用户信息
                const users = JSON.parse(sessionStorage.getItem('CurUser'))
                // 将当前用户的机构名赋值给 form 对象的 organization 属性
                this.form.organization = users.organization
            },

            resetForm() {
                this.$set(this.form, 'studentIdDisabled', false);
                this.$refs.form.resetFields();
            },

            del(id) {
                console.log(id);

                this.$axios.get('http://'+ serverIp +':8090/users/delete?id=' + id)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },

            mod(row) {
                console.log(row);

                this.centerDialogVisible = true
                this.$nextTick(() => {
                    //赋值到表单
                    this.form.id = row.id;
                    this.form.studentIdDisabled = true; // 禁用学号字段的输入框
                    this.form.studentId = row.studentId;
                    this.form.password = row.password;
                    this.form.name = row.name;
                    this.form.sex = row.sex + '';
                    this.form.age = row.age + '';
                    this.form.phoneNumber = row.phoneNumber;
                    this.form.userIdentity = row.userIdentity;
                    this.form.organization = row.organization;
                })
            },

            doMod() {
                this.$axios.post('http://'+ serverIp +':8090/users/update', this.form)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                        this.resetForm()
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },

            doSave() {
                this.$axios.post('http://'+ serverIp +':8090/users/save', this.form)
                    .then(res => res.data).then(res => {
                    console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            message: '操作成功！',
                            type: 'success'
                        });
                        this.centerDialogVisible = false;
                        this.loadPost();
                        this.resetForm()
                    } else {
                        this.$message({
                            message: '操作失败！',
                            type: 'error'
                        });
                    }
                })
            },

            save() {
                this.$refs.form.validate((valid) => {
                        if (valid) {
                            if (this.form.id) {
                                this.doMod();
                            } else {
                                this.doSave();
                            }
                        } else {
                            console.log('error!!!');
                            return false;
                        }
                    }
                )
            },

            add() {
                this.centerDialogVisible = true
                this.$nextTick(() => {
                    this.resetForm()
                    this.mounted()
                })
            },

            resetParam() {
                this.name = ''
                this.userIdentity = ''
                this.loadPost()
            },

            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum = 1
                this.pageSize = val
                this.loadPost()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum = val
                this.loadPost()
            },

            loadGet() {
                this.$axios.get('http://'+ serverIp +':8090/users/list').then(res => res.data).then(res => {
                    console.log(res)
                })
            },

            loadPost() {
                this.$axios.post('http://'+ serverIp +':8090/users/page', {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,
                    param: {
                        name: this.name,
                        userIdentity: this.userIdentity
                    }
                }).then(res => res.data).then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        this.tableData = res.data
                        this.total = res.total
                    } else {
                        alert('获取数据失败')
                    }

                })
            }
        },

        beforeMount() {
            // this.loadGet();
            this.loadPost();
        }
    }
</script>

<style scoped>

    .search {
        margin-bottom: 5px;
    }
</style>